package feng.demo.service;

import feng.demo.dao.CommodityDao;
import feng.demo.dao.RemarkDao;
import feng.demo.dao.UserDao;
import feng.demo.entity.Commodity;
import feng.demo.entity.Remark;
import feng.demo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
@Service
@CacheConfig(cacheNames = {"remark"})
public class RemarkServiceImpl implements RemarkService{
    @Autowired
    RemarkDao remarkDao;
    @Autowired
    UserDao userDao;
    @Autowired
    CommodityService commodityService;
    @Override
    @Cacheable
    public List<Remark> findAll() {
        List<Remark> all = remarkDao.findAll();
        return doadds(all);
    }

    @Override
    @Cacheable(key = "#p0")
    public Remark findById(Integer remid) {
        Remark remark = remarkDao.findById(remid);
        return doadd(remark);
    }

    @Override
    public List<Remark> findRemark(Map<String, Object> map) {
        List<Remark> remarks = remarkDao.findRemark(map);
        return doadds(remarks);
    }

    @Override
    @CacheEvict(value = "remark", allEntries = true)
    public int add(Remark remark) {
        return remarkDao.add(remark);
    }

    @Override
    @CacheEvict(value = "remark", allEntries = true)
    public int del(Integer remid) {
        return remarkDao.del(remid);
    }

    @Override
    @CacheEvict(value = "remark", allEntries = true)
    public int update(Remark remark) {
        return remarkDao.update(remark);
    }

    @Override
    @Cacheable
    public List<Remark> findByAllLimit(Integer pagenum, Integer lines) {
        List<Remark> list = remarkDao.findByAllLimit(pagenum, lines);

        return doadds(list);
    }

    @Override
    public int findCount() {
        return remarkDao.findCount();
    }

    @Override
    @Cacheable(key = "#p0")
    public List<Remark> findByComid(Integer comid) {
        List<Remark> remarks = remarkDao.findByComid(comid);
        return doadds(remarks);
    }

    private List<Remark> doadds(List<Remark> list){

        for (Remark r:list) {
            User user = userDao.findByUid(r.getUser().getUid());
            Commodity commodity = commodityService.findById(r.getCommodity().getComid());
            User u = userDao.findByUid(r.getCus().getUid());
            r.setUser(user);
            r.setCommodity(commodity);
            r.setCus(u);
        }
        return list;
    }
    private Remark doadd(Remark r){
        User user = userDao.findByUid(r.getUser().getUid());
        Commodity commodity = commodityService.findById(r.getCommodity().getComid());
        User u = userDao.findByUid(r.getCus().getUid());
        r.setUser(user);
        r.setCommodity(commodity);
        r.setCus(u);
        return r;

    }
}
